import { PiniaPluginContext } from "pinia";
type Store = PiniaPluginContext["store"];
const config = () => {
  return {
    enabled: true,
    strategies: [{ storage: localStorage }],
    exclude: [], //排除stores的id值
  };
};

export const updateStorage = (strategy: any, store: Store) => {
  const storage = strategy.storage || sessionStorage;
  const storeKey = strategy.key || store.$id;
  if (strategy.paths) {
    const partialState = strategy.paths.reduce((finalObj: any, key: string) => {
      finalObj[key] = store.$state[key];
      return finalObj;
    }, {});
    storage.setItem(storeKey, JSON.stringify(partialState));
  } else {
    storage.setItem(storeKey, JSON.stringify(store.$state));
  }
};

export default ({ store }: PiniaPluginContext) => {
  const options = config();
  if (options?.enabled && options?.exclude.join().indexOf(store.$id) < 0) {
    const defaultStrat = [
      {
        key: store.$id,
        storage: sessionStorage,
      },
    ];

    const strategies = options?.strategies?.length ? options?.strategies : defaultStrat;
    strategies.forEach((strategy: any) => {
      const storage = strategy.storage || sessionStorage;
      const storeKey = strategy.key || store.$id;
      const storageResult = storage.getItem(storeKey);
      if (storageResult) {
        store.$patch(JSON.parse(storageResult));
        updateStorage(strategy, store);
      }
    });

    store.$subscribe(() => {
      strategies.forEach((strategy) => {
        updateStorage(strategy, store);
      });
    });
  }
};
